//index.js
//获取应用实例
const app = getApp()
const cloudApi = require('../../utils/cloudApi.js');
const img = require('../../utils/img.js');

Page({
  data: {
    marginTop: 0, //计算头部标题栏高度
    itemList: [], //商品数组
    page: 'index', //判断分页内容
    image: img.image,
    slip: img.slip,
    isEnd: false,
    showLoading: true,
    jsonIndex: {
      "vekey": app.globalData.app_key_wytk,
      "subcate": '',  //二级分类
      "page": 1,
      "pagesize": 20,
      "para": ''
    },
    showDialog: {
      title: '',
      image: '',
      para: ''
    }
  },
  onShow: function() {
    //后台重新进入小程序，检测剪贴板
    this.getClipboard();
  },
  onLoad: function() {
    //获取头部margin
    this.setMarginTop();
    //显示加载动画
    this.setData({
      showLoading: true
    });
    //获取首页商品
    this.getItemList();
  },
  onShareAppMessage(res) {
    //注册转发小程序功能
    return {
      title: app.globalData.appName + '-首页',
      path: '/pages/index/index'
    }
  },
  onPullDownRefresh() {
    //停止下滑动画
    wx.stopPullDownRefresh();
    //初始化数据
    this.resetData();
    //获取首页商品
    this.getItemList();
  },
  onReachBottom() {
    //上拉加载数据
    if (this.data.page == 'index') {
      //分页加载首页商品
      this.getItemList();
    } else {
      //分页加载搜索商品
      this.searchItem();
    }
  },
  setSubcate(event){
    let subcate = event.currentTarget.dataset.subcate;
    //初始化数据
    this.resetData();
    this.setData({
      showLoading: true,
      "jsonIndex.subcate" : subcate,
    });
    //获取首页商品
    this.getItemList();
  },
  //执行搜索操作，获取搜索内容
  getSearchTxt(event) {
    this.resetData();
    this.data.page = 'search';
    this.setData({
      "jsonIndex.page": 1,
      "jsonIndex.para": event.detail.value,
    });
    //显示加载动画
    this.setData({
      showLoading: true
    });
    this.searchItem();
  },
  //首页默认展示列表
  getItemList() {
    wx.request({
      url: cloudApi.getAction('index', this.data.jsonIndex), //请求接口的url
      method: 'GET', //请求方式
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        let result = JSON.parse(res.data.Response.Result.RetMsg);
        //分页结束
        if (result.data.length < 1) {
          this.data.isEnd = true;
        };
        //数组连接
        var itemList = this.data.itemList.concat(result.data);
        this.setData({
          showLoading: false,
          itemList: itemList,
        });
        //页数+1
        this.data.jsonIndex.page += 1;
      }
    })
  },
  //搜索接口
  searchItem() {
    wx.request({
      url: cloudApi.getAction('search', this.data.jsonIndex), //请求接口的url
      method: 'GET', //请求方式
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        let result = JSON.parse(res.data.Response.Result.RetMsg);
        //分页结束
        if (result.result_list.length < 1) {
          this.data.isEnd = true;
        };
        //数组连接
        var itemList = this.data.itemList.concat(result.result_list);
        this.setData({
          showLoading: false,
          itemList: itemList
        });
        //页数+1
        this.data.jsonIndex.page += 1;
      }
    })
  },
  // 点击商品跳转详情页
  toDetail(event) {
    wx.navigateTo({
      url: '/pages/detail/detail?isShare=0&itemId=' + event.currentTarget.dataset.itemid
    })
  },
  resetData() {
    //滚动至顶部
    this.scrollToTop();
    //初始化页面数据
    this.data.itemList = [];
    this.data.isEnd = false;
    this.data.page = 'index';
    this.data.jsonIndex = {
      "vekey": app.globalData.app_key_wytk,
      "subcate": '',
      "page": 1,
      "pagesize": 20,
      "para": ''
    };
  },
  scrollToTop() {
    //滚动至顶部
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 500
    });
  },
  setMarginTop() {
    // 动态计算标题高度
    wx.getSystemInfo({
      success: ({
        statusBarHeight,
        system
      }) => {
        let titleBarHeight = 44
        if (system.indexOf('Android') !== -1) {
          titleBarHeight = 54
        }
        this.setData({
          'marginTop': titleBarHeight + statusBarHeight
        })
      }
    })
  },
  getClipboard(callback) {
    var that = this;
    wx.getClipboardData({
      success: function(res) {
        if (res.data.indexOf("€") != -1 || res.data.indexOf("￥") != -1) {
          var jsonDetail = {
            "vekey": app.globalData.app_key_wytk,
            "para": res.data
          };
          wx.request({
            url: cloudApi.getAction('detail', jsonDetail), //请求接口的url
            method: 'GET', //请求方式
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: res => {
              that.setData({
                showDialog: {
                  title: JSON.parse(res.data.Response.Result.RetMsg).data.title,
                  image: JSON.parse(res.data.Response.Result.RetMsg).data.pict_url,
                  para: JSON.parse(res.data.Response.Result.RetMsg).data.num_iid
                }
              });
              //清空剪贴板
              wx.setClipboardData({
                data: '.',  //手机下不能设置为空字符串
                success(res) {
                  wx.hideToast();
                }
              });
              that.showDialog();
            }
          })
        }
      },
    });
  },
  showDialog() {
    let dialogComponent = this.selectComponent('.wxc-dialog')
    dialogComponent && dialogComponent.show();
  },
  hideDialog() {
    let dialogComponent = this.selectComponent('.wxc-dialog')
    dialogComponent && dialogComponent.hide();
  },
  onConfirm() {
    this.hideDialog();
    var that = this;
    //跳转详情页面
    wx.navigateTo({
      url: '/pages/detail/detail?isShare=0&itemId=' + that.data.showDialog.para
    });
  },
  onCancel() {
    this.hideDialog();
  }
})